import { useMemo } from 'react'
import dayjs from 'dayjs'
import { Button } from 'antd'
import { ColDef, ICellRendererParams } from '@ag-grid-community/core'

import { CusAgGrid } from '@/components/CusAgGrid'
import { Texty } from '@/components/Texty'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import type { AttachListResultParam } from '../../interface'
import { getFileTypeName } from '../../utils'
/** columnDefs 配置项 */
export type TCol<T extends keyof AttachListResultParam = keyof AttachListResultParam> = ColDef<
  AttachListResultParam,
  AttachListResultParam[T]
> & {
  field: T
}

/** cellRendererParams */
export type TCellParams<T extends keyof AttachListResultParam = keyof AttachListResultParam> = ICellRendererParams<
  AttachListResultParam,
  AttachListResultParam[T]
>

interface IProps {
  /** 附件列表数据 */
  list: AttachListResultParam[]
  /** 是否自动高度 */
  boxAutoHeight?: boolean
}

/** 单元格渲染 */
const CellRender = (p: TCellParams) => {
  const { field } = p.colDef || {}
  const { data } = p
  if (data == null) return
  switch (field) {
    /** 文件名*/
    case 'fileName': {
      return (
        <Button style={{ overflow: 'hidden' }} type="link" target="_blank" href={data?.fileUrl as string}>
          <Texty>{data?.fileName}</Texty>
        </Button>
      )
    }
    /** 文件类型 */
    case 'fileType': {
      return <Texty>{getFileTypeName(Number(data?.fileType))}</Texty>
    }
    /** 备注 */
    case 'comment': {
      return <Texty>{data?.comment}</Texty>
    }
    /** 上传时间 */
    case 'uploadAt': {
      return <Texty>{data?.uploadAt ? dayjs(data?.uploadAt).format($F_YMDHms) : ''}</Texty>
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

export const List = (props: IProps) => {
  const { list, boxAutoHeight } = props
  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 180,
      sortable: false,
      cellRenderer: CellRender,
    }),
    [],
  )

  const columnDefs = useMemo(() => {
    const cols: TCol[] = [
      {
        field: 'fileName',
        headerName: '文件名',
        flex: 0.01,
        minWidth: 130,
      } satisfies TCol<'fileName'>,
      {
        field: 'fileType',
        headerName: '文件类型',
        flex: 0.01,
        minWidth: 80,
      } satisfies TCol<'fileType'>,
      {
        field: 'comment',
        headerName: '备注',
        flex: 0.01,
        minWidth: 100,
      } satisfies TCol<'comment'>,
      {
        field: 'uploadAt',
        headerName: '上传时间',
        flex: 0.01,
        minWidth: 150,
      } satisfies TCol<'uploadAt'>,
    ]

    return cols
  }, [list])

  return (
    <CusAgGrid<AttachListResultParam>
      rowData={list}
      defaultColDef={defaultColDef}
      columnDefs={columnDefs}
      rowHeight={54}
      cellSelection={false}
      domLayout={boxAutoHeight ? 'autoHeight' : undefined}
    />
  )
}
